﻿using System.Collections.Generic;
using System.IO;

namespace Vkontakte.Api.Operations
{
	[ApiMethod("friends.getLists")]
	public sealed class FriendsGetLists
		:Base30ApiOperation
	{
		private FriendsList[] _lists;

		protected override void Compile()
		{
			AddParameter("method", "friends.getLists");
			AddParameter( "format", "JSON" );
			base.Compile();
		}

		protected override void ParseData(string data)
		{
			List<FriendsList> ret=new List<FriendsList>();

			string sub = data.Substring( 1, data.Length - 2 );
			if (sub.StartsWith( "\"response\"" ))
			{
				int start = sub.IndexOf( ":{" );
				int end = sub.IndexOf( '}',start );
				string dt = sub.Substring( start+2, end-start-2 );

				string[] parts = dt.Split( ',' );
				for (int i=0;i<parts.Length;i++)
				{
					string[] IdAndName= parts[ i ].Split( ':' );
					FriendsList list=new FriendsList();
					list.ID = int.Parse( IdAndName[ 0 ].Substring( 1, IdAndName[ 0 ].Length - 2 ) );
					list.Name = IdAndName[ 1].Substring( 1, IdAndName[ 1 ].Length - 2 );
					list.Name = list.Name.FixJsonString();
					ret.Add( list );
				}
			}
			_lists = ret.ToArray();
			base.ParseData(data);
		}

		public FriendsList[] GetResult()
		{
			return _lists;
		}
	}
}
